﻿using CurriculaAPI.POCOModel;
using CurriculaAPI.ViewModelDTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace CurriculaAPI.Controllers
{
    public class StudentController : Controller
    {
        // GET: Student
        static string UName = "";
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UserLogin(string name, string pwd)
        {
            using (var db = new CurriculaEntity())
            {
                var user = db.StudentInfo.FirstOrDefault(s => s.Name == name && s.Password == pwd);
                UName = user.Name;
                if (user == null)
                {
                    return Json(new { State = -1, Message = "登录失败,没有该用户" });
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(name, false);
                    return Json(new { State = 1, Message = "登录成功" });
                }
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }
        /// <summary>
        /// 注册成功
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register(StudentInfoRegisterDTO dto)
        {
            if (ModelState.IsValid)
            {
                using (var db = new CurriculaEntity())
                {
                    var stu = new StudentInfo()
                    {
                        Name = dto.Name,
                        Sex = dto.Sex,
                        Address = dto.Address,
                        SNo = dto.SNo,
                        Password = dto.Password,
                        PhoneNum = dto.PhoneNum,
                        Pwd = dto.Pwd
                    };
                    db.StudentInfo.Add(stu);
                    db.SaveChanges();
                    ViewBag.msg = "注册成功";
                }
            }
            else
            {
                ModelState.AddModelError("", "注册失败");
            }
            return View(dto);
        }
    }
}